# -*- coding:utf8 -*-
#encoding = utf-8
__author__ = 'man'

#		_________________________________________________________________________________
#
#						漫鸽网络技术服务(mangenotwork)拥有所有权
#						@www.hbsj.xyz   
#						@www.mangenotwork.com
#			严重声明：原始代码属于"漫鸽网络技术服务(mangenotwork)"的知识产权，拥有法律的保护，
#		请勿抄袭、转载、删除、私用、篡改、破坏...
#
#       
#		简介 ：  user.py 用户模块API
#		作者 ： 李漫(man)
#		创建时间:  20190620
#		
#		_________________________________________________________________________________

from flask import Flask,request,g,render_template,redirect,url_for,abort,session,jsonify,current_app
from flask import Blueprint , render_template
from flask import make_response,Response 
import sys,os
import json
import time
import datetime
import redis
from cryptography.fernet import Fernet
import hashlib
import db.mandb
import random


'''
man_db = db.mandb.DB()
print(man_db.db_connect())
'''
user = Blueprint('user',__name__)

#函数不能命名 test

#公用方法
import api.public as pub

#图片处理方法
import api.compress_img as compress



'''
					#类型： DB交互
					#执行查询  查询结果
'''
def ManDB(func=None, param=None):
	def deco(func):
		def wrapper(*args,**kwargs):
			man_db = db.mandb.DB()
			return func(man_db,*args,**kwargs)			
		wrapper.__name__ = func.__name__
		return wrapper
	return deco if not func else deco(func)


#函数不能命名 test
@user.route('/user_test', methods=['POST','GET'])
def collect_test():
	return "This is a Blueprint : user Test."




# 我的主页 获取个人信息
@ManDB
def get_user_info(man_db,useruuid):
	sql = "select user_name,user_head,user_jifen from userinfo where user_uuid = '"+useruuid+"';"
	return_datas = man_db.execute_seles(sql)
	return return_datas[0]



#我的主页
@user.route('/my', methods=['POST','GET'])
def my_pg():
    
    if pub.userACC() == False:

        return redirect('/loginpg')
    else:
        useruuid=request.cookies.get('user_uuid')
        print(useruuid)
        userinfolist = get_user_info(useruuid)
        print(userinfolist)
        if userinfolist[1] != "0":
        	user_img = "http://hbsj.xyz/user_head/"+userinfolist[1]
        else:
        	user_img = "http://hbsj.xyz/h5/hbsjimg.png"
        '''
        userinfo = user_function.get_user_info(hbsj_user_id)
        if userinfo[1] == "0":
            userhead = "static/images/hbsjimg.png"
        else:
            userhead = userinfo[1]
        '''
        return render_template('my.html',my=1,username=userinfolist[0],headimg=user_img,jifen = userinfolist[2])
    '''
    return render_template('my.html',my=1,username="man",headimg="static/images/hbsjimg.png")
    '''


# 占时不上  更换名称



#获取推荐分类
@ManDB
def get_tj_fenlei(man_db):
    sql = "select flxd from app_home_flxd;"
    return_datas = man_db.execute_seles(sql)
    returnlist = []
    for data in return_datas:
        returnlist.append(data[0])
    return returnlist



#更换用户头像信息
@ManDB
def updata_userhead(man_db,useruuid, user_head):
    sql = "UPDATE userinfo set user_head = '"+user_head+"' where user_uuid = '"+useruuid+"' ;"
    man_db.execute(sql)
    print("[DeBug] updata_userhead")
    return 0




# 更换头像
@user.route('/changehead', methods=['POST','GET'])
def change_head():
    if request.method == 'POST':
        file = request.files['headimg']
        #ageval = request.form.get('ageval')
        #projectname = request.form.get('project_name')
        #branchname = request.form.get('branch_name')
        #username = request.form.get('user_handle_name')
    #name = datax["names"]
    #print(ageval)
    print(file)
    print(file.filename)

    userToken=request.cookies.get('user_token')
    print("userToken = "+ str(userToken))
    useruuid=request.cookies.get('user_uuid')
    print("userUUID = "+ str(useruuid))
    session_usertoken = session.get(useruuid)# 这个是保存的 user_token
    print("session_usertoken = "+ str(session_usertoken))
    if session_usertoken == userToken and userToken != None:

        if file != "" and compress.allowed_file(file.filename):
            returndata = 1
            newfilename = pub.set_user_uuid(str(time.time()))
            #保存到服务器
            #剪裁 图片
            print(newfilename)
            newfilename_info = compress.compressImg_2(file,newfilename,compress.get_filedis(file.filename))

            print(newfilename_info)

            #更新用户上传的信息

            updata_userhead(useruuid,newfilename_info)

        else:
            returndata = 0
    else:
        returndata = 2
    print("返回 ： "+ str(returndata))
    return json.dumps(returndata).encode('utf-8').decode("unicode-escape")



#打开修改头像
@user.route('/modifhead', methods=['POST','GET'])
def modifhead_pg():
    if pub.userACC() == False:

        return redirect('/loginpg')
    else:
        useruuid=request.cookies.get('user_uuid')
        print(useruuid)
        userinfolist = get_user_info(useruuid)
        print(userinfolist)
        if userinfolist[1] != "0":
            user_img = "http://hbsj.xyz/user_head/"+userinfolist[1]
        else:
            user_img = "http://hbsj.xyz/h5/hbsjimg.png"

    return render_template('modifhead.html',my=1,headimg=user_img)



#联系我们
@user.route('/aboutus', methods=['POST','GET'])
def aboutus_pg():
    return render_template('about_us.html',my=1)


#发布信息选择
@user.route('/fabuxz', methods=['POST','GET'])
def fabuxz_pg():
    if pub.userACC() == True:
        return render_template('fabu_xz.html',my=1)
    else:
        return redirect('/loginpg')


#发布信息
@user.route('/fabumain', methods=['POST','GET'])
def fabumain_pg():
    if request.method == "GET":
        xx = request.args.get('xxtype')
        mb = request.args.get('mbtype')
    print(xx)

    if xx == "fx":
        xx_info = "分享信息"
    elif xx == "rs":
        xx_info = "二手信息"
    elif xx == "zy":
        xx_info = "资源信息"
    elif xx == "gg":
        xx_info = "网络营销"
    else:
        return render_template('fabu_xz.html',my=1)

    print(mb)
    if mb == "1":
        return render_template('fabu_main.html',my=1,titleinfo=xx_info,mb1=1,sqtype=xx)
    elif mb == "2":
        return render_template('fabu_main.html',my=1,titleinfo=xx_info,mb2=1,sqtype=xx)
    elif mb == "3":
        return render_template('fabu_main.html',my=1,titleinfo=xx_info,mb3=1,sqtype=xx)
    elif mb == "4":
        return render_template('fabu_main.html',my=1,titleinfo=xx_info,mb4=1,sqtype=xx)
    else:
        return render_template('fabu_xz.html',my=1)



#发布信息图片保存与修改（名称，大小）
def fabu_addimgs(file):
    newfilename = pub.set_user_uuid(str(time.time())+str(random.randint(0,9)))
    #保存到服务器
    #剪裁 图片
    print(newfilename)
    newfilename_info = compress.compressImg_1000(file,newfilename,compress.get_filedis(file.filename))
    print(newfilename_info)
    return newfilename_info




#保存发布信息到数据库
@ManDB
def add_infos_to_db(man_db, addsq_info_id, useruuid, titles, sqtype, sendtime, maindata, img_todblist):
    sql = "INSERT INTO sq_main ( sqmian_id, user_uuid,sqtitle,sqtype,sq_sendtime,content,content_imgs) VALUES ('"+addsq_info_id+"', '"+useruuid+"', '"+titles+"', '"+sqtype+"', '"+sendtime+"', '"+maindata+"', '"+img_todblist+"');"
    man_db.execute(sql)
    print("[DeBug] updata_userhead")
    return 0



#发布信息
@user.route('/fabusetinfo/<number>', methods=['POST','GET'])
def fabusetinfo(number):
    print("fabusetinfo")

    #获取用户信息
    userToken=request.cookies.get('user_token')
    print("userToken = "+ str(userToken))
    useruuid=request.cookies.get('user_uuid')
    print("userUUID = "+ str(useruuid))
    session_usertoken = session.get(useruuid)# 这个是保存的 user_token
    print("session_usertoken = "+ str(session_usertoken))

    imglist = []
    if session_usertoken == userToken and userToken != None:
        if number == "1":
            if request.method == "POST":
                file1 = request.files['img1']
                titles = request.form["title"]
                maindata = request.form["maindata"]
                sqtype = request.form["sqtype"]
                imglist.append(file1)
            print(file1.filename)
        elif number == "2":
            if request.method == "POST":
                file1 = request.files['img1']
                file2 = request.files['img2']
                titles = request.form["title"]
                maindata = request.form["maindata"]
                sqtype = request.form["sqtype"]
                imglist.append(file1)
                imglist.append(file2)
            print(file1.filename)
            print(file2.filename)
        elif number == "4":
            if request.method == "POST":
                file1 = request.files['img1']
                file2 = request.files['img2']
                file3 = request.files['img3']
                file4 = request.files['img4']
                titles = request.form["title"]
                maindata = request.form["maindata"]
                sqtype = request.form["sqtype"]
                imglist.append(file1)
                imglist.append(file2)
                imglist.append(file3)
                imglist.append(file4)
            print(file1.filename)
            print(file2.filename)
            print(file3.filename)
            print(file4.filename)
        
        #发布的信息ID
        addsq_info_id = "InfoID_"+pub.set_user_uuid(str(time.time())+str(titles))
        print(addsq_info_id)
        print(titles)
        print(maindata)
        print(sqtype)
        print(imglist)
        #发布的时间
        sendtime = str(time.time())
        #存储图像的内容
        img_todblist = ""
        for imgobj in imglist:
            print(imgobj)
            imgnames = fabu_addimgs(imgobj)
            img_name = "#"+imgnames
            img_todblist += img_name
        print(img_todblist)

        #保存发布信息到数据库
        add_infos_to_db(addsq_info_id, useruuid, titles, sqtype, sendtime, maindata, img_todblist)

        return json.dumps(1).encode('utf-8').decode("unicode-escape")
    else:
        #如果发布接口没有识别到用户身份则返回 0 通知用户登陆
        return json.dumps(0).encode('utf-8').decode("unicode-escape")





